<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkMessage\Action\Dashboard\Config;

use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Tenant\Contract\TenantContract;
use MoChat\App\Utils\Url;
use MoChat\App\WorkMessage\Contract\WorkMessageConfigContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 会话存档配置-获取可信IP地址、接收事件服务器.
 *
 * Class GetServerIps.
 * @Controller
 */
class GetMessageConfig extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var TenantContract
     */
    protected $tenantService;

    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @Inject
     * @var WorkMessageConfigContract
     */
    protected $workMessageConfigService;

    /**
     * @Inject
     * @var ConfigInterface
     */
    protected $config;

    /**
     * @RequestMapping(path="/dashboard/workMessageConfig/getMessageConfig", methods="get")
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        // 参数验证
        $this->validated($this->request->all());
        $corpIds = user('corpIds');
        if (count($corpIds) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '请选择一个企业，再进行操作');
        }

        // 获取当前登录用户
        $user = user();
        $tenantId = $user['tenantId'];
        $tenant = $this->tenantService->getTenantById($tenantId, ['server_ips']);
        if (! empty($tenant) && ! empty($tenant['serverIps'])) {
            $serverIps = Json::decode($tenant['serverIps']);
        } else {
            $serverIps = config('server.ip');
            $serverIps = explode(',', $serverIps);
        }

        $corp = $this->corpService->getCorpById(user('corpIds')[0], ['id', 'token', 'encoding_aes_key']);

        $info = $this->workMessageConfigService->getWorkMessageConfigByCorpId(user('corpIds')[0], ['id', 'chat_rsa_key', 'chat_secret']);
        $key = [];
        $allChatRsaKey = [];
        if (! empty($info['chatRsaKey'])) {
            $chatRsaKey = Json::decode($info['chatRsaKey']);
        } else {
            $chatRsaKey['version'] = '';
            [$chatRsaKey['privateKey'], $chatRsaKey['publicKey']] = rsa_keys();
        }

        if (count($chatRsaKey) === count($chatRsaKey, 1)) {
            $key = $chatRsaKey;
            $allChatRsaKey = [$chatRsaKey];
        } else {
            $key = end($chatRsaKey);
            $allChatRsaKey = $chatRsaKey;
        }

        return [
            'serverIps' => $serverIps,
            'url' => Url::getApiBaseUrl() . '/' . ltrim(config('framework.wework.callback_path'), '/') . '?cid=' . user('corpIds')[0],
            'token' => $corp['token'] ?? '',
            'encodingAESKey' => $corp['encodingAesKey'] ?? '',
            'chatRsaKey' => $key,
            'allChatRsaKey' => $allChatRsaKey,
            'chatSecret' => $info['chatSecret'],
        ];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [];
    }
}
